package com.jin.jpa.wrapper.expression;

import com.jin.jpa.wrapper.LambdaWrapperContext;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.Path;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

/**
 * @Author: yuanxiuyao
 * @Date: 2024/1/8 16:31
 * @PackageName: org.example.jpa.wrapper.expression
 * @Version 1.0
 */
public class WhereExpression implements IExpression<Predicate>{

    private String field;

    private WhereOp whereOp;

    private Object value;

    private WhereExpression(String field, Object value, WhereOp whereOp){
        this.field = field;
        this.whereOp = whereOp;
        this.value = value;
    }

    public static WhereExpression of(String field, Object value, WhereOp whereOp){
        return new WhereExpression(field, value, whereOp);
    }

    @Override
    public Predicate toHandle(LambdaWrapperContext<?> context) {
        Root<?> root = context.getRoot();
        CriteriaBuilder criteriaBuilder = context.getCriteriaBuilder();
        Path<?> expression = root.get(field);
        switch (whereOp) {
            case EQ:
                return criteriaBuilder.equal(expression, value);
            case IS_NULL:
                return criteriaBuilder.isNull(expression);
            case IS_NOT_NULL:
                return criteriaBuilder.isNotNull(expression);
        }
        return null;
    }

    public enum WhereOp{
        EQ,
        IS_NULL,
        IS_NOT_NULL
    }
}
